package com.eudemon.taurus.app.action;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.eudemon.taurus.app.entities.OperResult;
import com.eudemon.taurus.app.service.OSSService;
import com.eudemon.taurus.app.utils.JasonUtils;

/**
 * 使用自己封装的方法（fastjson）返回json及jsonp格式的数据
 * 
 * @author eric
 *
 */
@Controller
@RequestMapping(value = "/api/oss/")
public class OSSApiAction {
	private Logger logger = LoggerFactory.getLogger(OSSApiAction.class);

	@Autowired
	private OSSService sv;

	@PostMapping(value = "upload")
	public void upload(@RequestParam("files") MultipartFile[] files, String path, HttpServletRequest request,
			HttpServletResponse response) {
		OperResult or = new OperResult();
		logger.debug("files:" + files.length);
		System.out.println("files:" + files.length);

		try {
			for(MultipartFile file : files){
				logger.debug("file:" + file.getOriginalFilename());
				sv.uploadObjectWjb(file, path);
			}
		} catch (Exception e) {
			logger.error("OSS upload Exception : " + e.getMessage(), e);
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage("OSS upload Exception : " + e.getMessage());
		} finally {
			JasonUtils.writeJasonP(request, response, or);
		}
	}

	@GetMapping(value = "download")
	public void download(@RequestParam String objNameFile, HttpServletRequest request, HttpServletResponse response) {
		OperResult or = new OperResult();

		try {
			List<String> objNameList = FileUtils.readLines(new File(objNameFile));
			for (String objName : objNameList) {
				sv.downloadObjectWjb(objName);
			}
		} catch (Exception e) {
			logger.error("OSS download Exception : " + e.getMessage(), e);
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage("OSS download Exception : " + e.getMessage());
		} finally {
			JasonUtils.writeJasonP(request, response, or);
		}
	}
}